import { Sequelize } from 'sequelize'
import { loggerFactory } from '@/util/Log4jsUtil'

/**
 * 创建sqlite连接(如果dbFilePath文件不存在，则会自动创建该文件[即使这个路径中包含尚不存在的目录也会一起创建])
 * @param dbFilePath 数据库文件绝对路径. 如: D:/sqliteDb/archives.db
 * @param loggerCategory sqlite日志分类标识
 */
export const sqliteSequelizeFactory = (
  dbFilePath: string,
  loggerCategory = 'sqliteLog'
): Sequelize => {
  const logger = loggerFactory(loggerCategory)
  logger.debug(`数据库文件路径: ${dbFilePath}`)
  const instance = new Sequelize({
    dialect: 'sqlite',
    storage: dbFilePath,
    logging: (...msg) => logger.debug(msg),
  })

  return instance
}

/**
 * 测试sqlite的数据库连接是否正常
 * @param instance
 */
export const testSqliteDbConnection = async (instance: Sequelize) => {
  // 测试连接是否正常
  await instance.authenticate()
}

/**
 * 创建所有表
 * @param instance
 * @param force 值为true时，如果表已经存在，则删除之后再创建. 默认: false
 */
export const createAllTable = async (instance: Sequelize, force = false) =>
  await instance.sync({ force })

/**
 * 删除所有表
 * @param instance
 */
export const dropAllTable = async (instance: Sequelize) => await instance.drop()

/**
 * 关闭Sqlite连接
 * @param instance
 */
export const closeSqliteConnection = async (instance: Sequelize) =>
  await instance.close()
